package net.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import net.dao.PesoHectolitricoDao;
import net.model.Objeto;
import net.model.PesoHectolitrico;

@Repository(value = "pesoHectolitricoDao")
public class PesoHectolitricoDaoImpl implements PesoHectolitricoDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public List<PesoHectolitrico> getAllPesoHectolitrico() {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
				PesoHectolitrico.class);
		return (List<PesoHectolitrico>) criteria.list();
	}

	@Override
	public void savePesoHectolitrico(PesoHectolitrico pesoHectolitrico) {
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(pesoHectolitrico);
		} catch (org.hibernate.NonUniqueObjectException e) {
			reattachToHibernateSession(pesoHectolitrico);
		}

	}

	public void reattachToHibernateSession(PesoHectolitrico pesoHectolitrico) {
		if (pesoHectolitrico != null && pesoHectolitrico.getId() != 0) {
			if (!sessionFactory.getCurrentSession().contains(pesoHectolitrico)) {
				Object oldObj = sessionFactory.getCurrentSession().get(
						pesoHectolitrico.getClass(), pesoHectolitrico.getId());
				if (oldObj != null) {
					sessionFactory.getCurrentSession().evict(oldObj);
				}
				sessionFactory.getCurrentSession().lock(pesoHectolitrico,
						LockMode.NONE);
			}
		}
	}
}
